<template>
  <div class="mt-2">
    <List @load="loadData" :loading="loading" :finished="finished" :finished-text="'没有更多了'">
      <OrderItem v-for="item in orderList" :key="item.id" :item="item" @ok="loadData()" />
    </List>
  </div>
</template>

<script setup lang="ts">
import OrderItem from './OrderItem.vue'
import { getIndexApi, getOrderApi } from '@/apis/collection'
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { List } from 'vant'
import { useAppStore } from '@/stores/app'

const { getTakeInfo } = useAppStore()

const props = defineProps({
  orderStatus: {
    type: Number,
    default: 0
  }
})

const orderList = ref([])
const page = ref(1)
const pageSize = ref(1000)
let timer = 0
const loading = ref(false)
const finished = ref(false)


function loadData() {
  loading.value = true
  if (props.orderStatus === 0 || props.orderStatus === 1) {
    getIndexApi({
      page: page.value,
      pageSize: pageSize.value,
      orderStatus: props.orderStatus
    }).then((res: any) => {
      orderList.value = res.list
      finished.value = true
    })
      .finally(() => {
        loading.value = false
      })
  } else {
    getOrderApi({
      page: page.value,
      pageSize: pageSize.value,
      orderStatus: props.orderStatus
    }).then((res: any) => {
      orderList.value = res.list
      finished.value = true
    })
      .finally(() => {
        loading.value = false
      })
  }
}

watch(
  () => props.orderStatus,
  () => {
    page.value = 1
    finished.value = false
    orderList.value = []
    loadData()
  }
)

watch(
  () => getTakeInfo.takeOrders,
  (newVal) => {
    if (newVal == '1') {
      refreshList()
    }
  }
)

function refreshList() {
  if (getTakeInfo.takeOrders != '1') {
    clearTimeout(timer)
    return
  }
  timer = setTimeout(() => {
    loadData()
    refreshList()
  }, 1000)
}

async function searchOrderExport(order: string) {
  if (!order) return
  // 停止自动接单刷新
  clearTimeout(timer)
  clearTimeout(timer)
  clearTimeout(timer)

  orderList.value = []

  let data = []
  const resp1 = await getIndexApi({
    page: 1,
    pageSize: 1000,
    orderNo: order
  })
  data = data.concat(resp1.list)
  const resp2 = await getOrderApi({
    page: 1,
    pageSize: 1000,
    orderNo: order
  })

  data = data.concat(resp2.list)

  orderList.value = data
}

function startRefreshList() {
  refreshList()
}

defineExpose({ searchOrderExport, startRefreshList })

onMounted(() => {
  loadData()
  refreshList()
})

onUnmounted(() => {
  clearTimeout(timer)
})
</script>
